package com.wuxinwudai.android.database;

import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;

/**
 * SmsCodeObserver 类为短信验证码观察者类
 * @author 吾心无待 于 2016年04月10日
 */
public class SmsCodeObserver extends ContentObserver{

    public final static int SEND_SMS_VERIFICATION_CODE_MESSAGE = 1;

    //#region 私有成员
    private Context context;
    private Handler handler;
    private String pattern;
    private String requestMobile;
    //#endregion

    /**
     * 构造函数，初始化 SmsCodeObserver 类的一个新实例
     * @param context 上下文对象
     * @param handler handler 消息处理器，应发送 HandlerMessages.SEND_SMS_VERIFICATION_CODE_MESSAGE 消息
     * @param requestMobile 发送的手机号码
     * @param pattern 验证码的匹配格式
     */
    public SmsCodeObserver(Context context,Handler handler,String requestMobile,String pattern){
        super(handler);
        this.context = context;
        this.handler = handler;
        this.requestMobile = requestMobile;
        this.pattern = pattern;
    }

    /**
     * 内容改变是调用该方法
     * @param selfChange 是否自我通知
     * @param uri 改变成 uri
     */
    public void onChange(boolean selfChange,URI uri){
        super.onChange(selfChange);
        if(uri.toString().equals("content://sms/raw")){
            return;
        }
        Uri inboxUri = Uri.parse("content://sms/inbox");//收信箱Uri
        Cursor c = context.getContentResolver().query(inboxUri,null,null,null,"date desc");
        if(c != null){
            if(c.moveToFirst()){
                String address = c.getString(c.getColumnIndex("address"));
                String body = c.getString(c.getColumnIndex("body"));
                if(!address.equals(requestMobile)) {
                    return;//不是请求的手机号码则返回
                }
                Pattern p = Pattern.compile(pattern);
                Matcher matcher = p.matcher(body);
                String code = "";
                if(matcher.find()){
                    code = matcher.group(0);
                    handler.obtainMessage(SEND_SMS_VERIFICATION_CODE_MESSAGE,code).sendToTarget();
                }
            }
            c.close();
        }
    }

}
